# 将静态手势打包，仿照cifar.npz的形式
import os
import numpy as np
from PIL import Image


dataset_dir = 'D:/Datasets/GestureNumber/'
dir_train_clean = dataset_dir + 'train_clean/'
dir_train_other = dataset_dir + 'train_other/'
dir_test = dataset_dir + 'test/'


# 根据图片文件列表读取图片内容，并根据文件名建立标签，返回numpy数组
def imgs_to_numpy(dirs):
	imgs = np.array([], dtype = np.uint8)
	labels = []
	for dir in dirs:
		img = Image.open(dir)
		img_arr = np.asarray(img)
		img_arr = np.reshape(img_arr, [-1, 32*32])
		if (imgs.size == 0):
			imgs = img_arr
		else:
			imgs = np.vstack((imgs, img_arr))

		# 注意label值从0开始
		labels.append(int(dir.split('/')[-1][0:2]) - 1)
		print(dir)

	return imgs, np.array(labels, dtype = np.int8)


# 读取图片文件列表，返回一个打乱顺序的训练集图片文件名列表和一个打乱顺序的验证集图片文件名列表
def random_imgs_list():
	train_list = [os.path.join(dir_train_clean, file) for file in os.listdir(dir_train_clean)] + [os.path.join(dir_train_other, file) for file in os.listdir(dir_train_other)]
	valid_list = [os.path.join(dir_test, file) for file in os.listdir(dir_test)]
	np.random.shuffle(train_list)
	np.random.shuffle(valid_list)
	return train_list, valid_list


def main():
	train_dirs, valid_dirs = random_imgs_list()
	train_images, train_labels = imgs_to_numpy(train_dirs)
	validation_images, validation_labels = imgs_to_numpy(valid_dirs)
	np.savez_compressed(dataset_dir + 'gesture', train_images=train_images, validation_images=validation_images,
                    train_labels=train_labels, validation_labels=validation_labels)


if __name__ == '__main__':
    main()
